﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace TouchPoint.Foundation
{
    public sealed class LimitedStack<T> : IEnumerable<T>
    {
        T[] _array;
        int _capacity;
        int _length;

        public LimitedStack():this(32) { }

        public LimitedStack(int capacity)
        {
            _capacity = capacity;
            _array = new T[_capacity];
            _length = 0;
        }

        public void Push(T item)
        {
            _array[_length % _capacity] = item;
            if (_length < _capacity) _length++;
        }

        public T Pop()
        {
            if (_length > 0) {
                return _array[_length--];
            }
            return default(T);
        }

        public int Count {
            get {
                return _length;
            }
        }

        public int Capacity {
            get {
                return _capacity;
            }
            set {
                _capacity = value;
            }
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (int i = _length - 1; i > 0; i--) {
                yield return _array[i];
            }
            yield break;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            for (int i = _length - 1; i > 0; i--) {
                yield return _array[i];
            }
            yield break;
        }
    }
}
